package com.jkt.rms.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.jkt.rms.commons.utils.ExceptionFactory;
import com.jkt.rms.commons.utils.RMSException;

public class AbstractMultiActionController extends MultiActionController {

	private static final Logger LOG = Logger.getLogger(AbstractMultiActionController.class);
	protected BindingResult errors;
	protected Validator multControllerValidator;

	public BindingResult getErrors() {
		return errors;
	}

	public void setErrors(BindingResult errors) {
		this.errors = errors;
	}

	public void setMultControllerValidator(Validator _validator) {
		this.multControllerValidator = _validator;
		this.setValidators(new Validator[] { this.multControllerValidator });
	}

	@Override
	protected void bind(HttpServletRequest request, Object command)
			throws RMSException {
		ServletRequestDataBinder binder = null;
		try {
			binder = createBinder(request, command);
			binder.bind(request);
			errors = binder.getBindingResult();
		} catch (Exception e) {
			ExceptionFactory.createRMSException(LOG, e.getCause(), "");
		}
	}

	public void validate(Object command) {
		Validator[] validators = getValidators();
		if (validators != null) {
			for (int index = 0; index < validators.length; index++) {
				Validator validator = validators[index];
				if (validator.supports(command.getClass())) {
					ValidationUtils.invokeValidator(validators[index], command,
							errors);
				}
			}
		}
	}

}
